//
//  HXDEmoticon.swift
//  weibo
//
//  Created by huxuedong on 15/12/15.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

class HXDEmoticon: NSObject, NSCoding {
    
    //表情描述
    var chs: String?
    //图片名称
    var png: String?
    //表情类型，0代表图片，1代表Emoji
    var type: String? {
        didSet {
            if type == "1" {
                isEmoji = true
            }
        }
    }
    //Emoji表情字符串
    var code: String?
    var path: String? {
        didSet {
            if png != nil {
                //此处要强制解包，否则获取不到正确的路径
                fullPath = "\(path!)/\(png!)"
            }
        }
    }
    var fullPath: String?
    var isEmoji: Bool = false
    
    init(dict: [String: AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
        type = aDecoder.decodeObjectForKey("type") as? String
        code = aDecoder.decodeObjectForKey("code") as? String
        path = aDecoder.decodeObjectForKey("path") as? String
        fullPath = aDecoder.decodeObjectForKey("fullPath") as? String
        isEmoji = aDecoder.decodeBoolForKey("isEmoji")
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(type, forKey: "type")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(path, forKey: "path")
        aCoder.encodeObject(fullPath, forKey: "fullPath")
        aCoder.encodeBool(isEmoji, forKey: "isEmoji")
    }
    
    override func isEqual(object: AnyObject?) -> Bool {
        guard let other = object as? HXDEmoticon else {
            return super.isEqual(object)
        }
        //同为Emoji图片或同为普通图片
        if other.isEmoji == isEmoji {
            //如果是Emoji图片
            if other.isEmoji {
                return (other.code! as NSString).isEqualToString(code!)
            } else {
                return (other.chs! as NSString).isEqualToString(chs!)
            }
        }
        return super.isEqual(object)
    }

}
